package com.wangmei.interceptor;


import com.wangmei.pojo.UserSimplify;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import unitTool.Dictionary;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    public static final String LOGIN_PAGE = "/login.html";
    public static final String MANAGE_PAGE = "/admin/index.html";
    public static final String SHOP_PAGE = "/shop/index.html";

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        System.out.println("开始拦截");
        String contextPath = httpServletRequest.getServletPath().toString();
        UserSimplify us = (UserSimplify) httpServletRequest.getSession().getAttribute(Dictionary.SessionKey.CURRENT_USER);
        if (us != null) {
            System.out.println("存在登录用户");
            if (us.getRid() != 1) {
                if (MANAGE_PAGE.equals(contextPath)) {
                    httpServletResponse.sendRedirect(SHOP_PAGE);
                }
            }
            return true;
        }


        System.out.println("请求路径：" + contextPath);
        httpServletResponse.sendRedirect(LOGIN_PAGE);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
